package com.timing;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.game.majiang.config.LogManager;
import com.robot.RobotClient;

import com.robot.RobotManager;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class RobotTask extends TimingTasks {

  private HashMap<Integer, RobotClient> clients = new HashMap<Integer, RobotClient>();

  public RobotTask() {
    super();
    // 添加定时器定时清除非活跃机器人
    this.threadPool.scheduleWithFixedDelay(new TimeEvent(), 5L, 1L, TimeUnit.SECONDS);
  }

  class TimeEvent implements Runnable {

    @Override
    public void run() {
      Collection<RobotClient> tempListClient = getClients();
      ArrayList<Integer> listDropLineUid = new ArrayList<Integer>();
      for (RobotClient robotClient : tempListClient) {
        try {
          robotClient.timeEvent();
          if (robotClient.getClient().getTable() == null) { // 移除非活跃（不在房间的）机器人
            listDropLineUid.add(robotClient.getClient().getUserId());
          }
        } catch (Exception e) {
          LogManager.getInstance().errorLog(e);
        }
      }
      for (Integer integer : listDropLineUid) {
        clients.remove(integer);
        RobotManager.getInstance().restockRobot(integer); // 回收机器人
      }
    }
  }

  @SuppressWarnings("unchecked")
  public Collection<RobotClient> getClients() {
    synchronized (this) {
      return ((HashMap<Integer, RobotClient>) clients.clone()).values();
    }
  }

  public HashMap<Integer, RobotClient> getClientMap() {
    synchronized (this) {
      return ((HashMap<Integer, RobotClient>) clients.clone());
    }
  }

  public boolean addClient(RobotClient robot) {
    if (this.clients == null) return false;
    synchronized (this.clients) { // 同步处理
      RobotClient robotClient = this.clients.get(robot.getClient().getUserId());
      if (robotClient == null) {
        this.clients.put(robot.getClient().getUserId(), robot);
        return true;
      } else {
        return false;
      }
    }
  }
}
